#!/bin/bash

#need automake,autoconf,libtool,libssl-dev installed.
which automake
if [ 0 -ne $? ]; then
	echo "automake was not installed."
	exit 1
fi

which autoconf
if [ 0 -ne $? ]; then
	echo "autoconf was not installed."
	exit 1
fi

which libtoolize 
if [ 0 -ne $? ]; then
	echo "libtool was not installed."
	exit 1
fi
echo "automake & autoconf & libtool is installed."


currentdir=$(cd "$(dirname "$0")"; pwd)
echo "build directory: ${currentdir}."

echo -e "\nbuild libevent..."
if [ ! -d "$currentdir/build" ]; then 
	mkdir "$currentdir/build"
else
	rm -rf ${currentdir}/build/*
fi

NDK="/opt/android-ndk-r25c"
# Only choose one of these, depending on your build machine...
export TOOLCHAIN=$NDK/toolchains/llvm/prebuilt/linux-x86_64
# Only choose one of these, depending on your device...
#export TARGET=aarch64-linux-android
export TARGET=armv7a-linux-androideabi
#export TARGET=i686-linux-android
#export TARGET=x86_64-linux-android
# Set this to your minSdkVersion.
export API=24
# Configure and build.
export AR=$TOOLCHAIN/bin/llvm-ar
export CC=$TOOLCHAIN/bin/$TARGET$API-clang
export AS=$CC
export CXX=$TOOLCHAIN/bin/$TARGET$API-clang++
export LD=$TOOLCHAIN/bin/ld
export RANLIB=$TOOLCHAIN/bin/llvm-ranlib
export STRIP=$TOOLCHAIN/bin/llvm-strip
#./configure --host $TARGET
#make
 	
autoreconf
./configure CFLAGS=-fPIC --disable-openssl --disable-samples --enable-shared=no --enable-function-sections --prefix=/usr/local --host $TARGET
make
make install DESTDIR=$currentdir/build

if [ ! -f "$currentdir/build/usr/local/lib/libevent_core.a" ]; then exit 1; fi
rm -rf ${currentdir}/../../../lib/libevent*.a
cp -v $currentdir/build/usr/local/lib/libevent_core.a ${currentdir}/../../../lib
cp -v $currentdir/build/usr/local/lib/libevent_pthreads.a ${currentdir}/../../../lib
cp -v $currentdir/build/usr/local/lib/libevent_extra.a ${currentdir}/../../../lib
if [ -f "$currentdir/build/usr/local/lib/libevent_openssl.a" ]; then
	cp -v $currentdir/build/usr/local/lib/libevent_openssl.a ${currentdir}/../../../lib
fi

make clean
rm -rf ${currentdir}/build/*

echo "====== libevent build success! ======"
exit 0
